<script setup lang="ts">
// 引入vue相关功能
import { ref, computed, onMounted } from 'vue'
// 引入vue-router用于获取路由参数
import { useRoute, useRouter } from 'vue-router'
import { ChatDotRound } from '@element-plus/icons-vue'

// 获取路由实例
const route = useRoute()
const router = useRouter()

// 用户详情数据，从路由参数获取
const userDetail = ref({
  name: '',
  avatar: '',
  level: 0,
  followed: false
})

// 顶部tab切换，notes为笔记，videos为视频
const detailTab = ref<'notes' | 'videos'>('notes')

// 视频数据示例，添加liked属性用于交互
const videoList = ref([
  {
    cover: 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=400&q=80',
    title: '3公里新手燃脂跑 学会如何轻松坚持',
    liked: false,
    duration: '4:30'
  },
  {
    cover: 'https://images.unsplash.com/photo-1517649763962-0c623066013b?auto=format&fit=crop&w=400&q=80',
    title: '3公里法特莱克跑',
    liked: false,
    duration: '5:15'
  },
  {
    cover: 'https://images.unsplash.com/photo-1464983953574-0892a716854b?auto=format&fit=crop&w=400&q=80',
    title: '马拉松优化跑姿',
    liked: false,
    duration: '7:20'
  },
  {
    cover: 'https://images.unsplash.com/photo-1526401485004-46910ecc8e51?auto=format&fit=crop&w=400&q=80',
    title: '200米 跨栏挑战',
    liked: false,
    duration: '3:45'
  },
  {
    cover: 'https://images.unsplash.com/photo-1576678927484-cc907957088c?auto=format&fit=crop&w=400&q=80',
    title: '家庭徒手力量训练 30分钟完整版',
    liked: false,
    duration: '30:15'
  },
  {
    cover: 'https://images.unsplash.com/photo-1518611012118-696072aa579a?auto=format&fit=crop&w=400&q=80',
    title: '高强度间歇训练HIIT 20分钟燃脂',
    liked: false,
    duration: '20:45'
  },
  {
    cover: 'https://images.unsplash.com/photo-1594737625785-a6cbdabd333c?auto=format&fit=crop&w=400&q=80',
    title: '初学者瑜伽指南 提高身体柔韧性',
    liked: false,
    duration: '35:10'
  },
  {
    cover: 'https://images.unsplash.com/photo-1574680096145-d05b474e2155?auto=format&fit=crop&w=400&q=80',
    title: '专业拉伸指南 运动前后必做',
    liked: false,
    duration: '15:30'
  }
])

// 用户笔记数据
const userPosts = ref([
  {
    id: 1,
    content: '今天完成了5公里跑步，感觉很棒！ 👍',
    image: 'https://images.unsplash.com/photo-1464983953574-0892a716854b?auto=format&fit=crop&w=400&q=80',
    time: '2小时前',
    likes: 12,
    comments: 3
  },
  {
    id: 2,
    content: '分享一个增肌训练计划，连续训练两周，肌肉线条明显提升！💪',
    image: 'https://images.unsplash.com/photo-1541534741688-6078c6bfb5c5?auto=format&fit=crop&w=400&q=80',
    time: '昨天',
    likes: 45,
    comments: 8
  },
  {
    id: 3,
    content: '早晨瑜伽打卡第30天，身体柔韧性有了很大提升，推荐大家每天坚持！🧘‍♀️',
    image: 'https://images.unsplash.com/photo-1506126613408-eca07ce68773?auto=format&fit=crop&w=400&q=80',
    time: '3天前',
    likes: 67,
    comments: 15
  },
  {
    id: 4,
    content: '周末参加了半程马拉松比赛，完赛成绩1小时52分，比上次提高了5分钟！🏃‍♂️🏅',
    image: 'https://images.unsplash.com/photo-1452626038306-9aae5e071dd3?auto=format&fit=crop&w=400&q=80',
    time: '5天前',
    likes: 89,
    comments: 23
  }
])

// 用户统计数据
const userStats = ref({
  following: 128,
  followers: 1200,
  posts: 56
})

// 页面加载时获取路由参数
onMounted(() => {
  // 从路由query参数中获取用户数据
  const { name, avatar, level, followed } = route.query
  if (name && avatar && level) {
    userDetail.value = {
      name: name as string,
      avatar: avatar as string,
      level: parseInt(level as string),
      followed: followed === 'true'
    }
    
    // 从本地存储加载关注状态
    try {
      const storedDataStr = localStorage.getItem('followedUsers');
      if (storedDataStr) {
        const followedUsers = JSON.parse(storedDataStr);
        if (followedUsers[userDetail.value.name]) {
          userDetail.value.followed = true;
        }
      }
    } catch (error) {
      console.error('加载关注状态失败:', error);
    }
  } else {
    // 如果没有参数，返回上一页
    router.back()
  }
})

// 返回上一页，携带用户关注状态
function goBack() {
  // 如果用户数据存在，将当前关注状态传回上一页
  if (userDetail.value.name) {
    router.push({
      path: '/community',
      query: {
        updatedUser: JSON.stringify({
          name: userDetail.value.name,
          followed: userDetail.value.followed
        })
      }
    })
  } else {
    router.back()
  }
}

// 关注/取消关注
function toggleFollow() {
  userDetail.value.followed = !userDetail.value.followed
  
  // 更新用户统计数据
  if (userDetail.value.followed) {
    userStats.value.followers += 1
  } else if (userStats.value.followers > 0) {
    userStats.value.followers -= 1
  }
  
  // 保存关注状态到localStorage
  try {
    const storedDataStr = localStorage.getItem('followedUsers') || '{}';
    const storedData = JSON.parse(storedDataStr);
    
    if (userDetail.value.followed) {
      storedData[userDetail.value.name] = true;
    } else {
      delete storedData[userDetail.value.name];
    }
    
    localStorage.setItem('followedUsers', JSON.stringify(storedData));
    console.log('已更新本地存储的关注状态:', storedData);
  } catch (error) {
    console.error('保存关注状态失败:', error);
  }
}

// 点赞视频
function toggleVideoLike(video: any) {
  video.liked = !video.liked
}

// 格式化关注者数量
const formattedFollowers = computed(() => {
  const count = userStats.value.followers
  return count >= 1000 ? (count / 1000).toFixed(1) + 'k' : count
})

// 聊天按钮点击事件，点击后跳转到聊天页面
function openChat(user: any) {
  router.push({
    path: '/chat',
    query: { name: user.name, avatar: user.avatar }
  })
}
</script>

<template>
  <div class="detail">
    <!-- 顶部导航栏 -->
    <div class="header">
      <button class="back-btn" @click="goBack">←</button>
      <span class="title">用户详情</span>
    </div>

    <!-- 用户信息卡片 -->
    <div class="user-card">
      <!-- 头像区域 -->
      <div class="avatar-section">
        <img :src="userDetail.avatar" alt="avatar" class="detail-avatar" />
        <div class="user-info">
          <h2 class="user-name">{{ userDetail.name }}</h2>
          <p class="user-level">等级：Lv.{{ userDetail.level }}</p>
        </div>
      </div>

      <!-- 关注按钮 -->
      <div class="actions">
        <button class="follow-btn" :class="{ followed: userDetail.followed }" @click="toggleFollow">
          {{ userDetail.followed ? '已关注' : '+关注' }}
        </button>
        <!-- 聊天按钮：已关注时显示为聊天图标 -->
        <button
          v-if="userDetail.followed"
          class="chat-btn"
          @click="openChat(userDetail)"
          title="聊天"
        >
          <el-icon><ChatDotRound /></el-icon>
        </button>
      </div>
    </div>

    <!-- tab切换栏 -->
    <div class="detail-tabs">
      <span :class="['tab', { active: detailTab === 'notes' }]" @click="detailTab = 'notes'">笔记</span>
      <span :class="['tab', { active: detailTab === 'videos' }]" @click="detailTab = 'videos'">视频</span>
    </div>

    <!-- tab内容区 -->
    <div class="tab-content">
      <!-- 笔记tab内容 -->
      <div v-if="detailTab === 'notes'">
        <!-- 用户统计信息 -->
        <div class="stats">
          <div class="stat-item">
            <span class="stat-number">{{ userStats.following }}</span>
            <span class="stat-label">关注</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ formattedFollowers }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ userStats.posts }}</span>
            <span class="stat-label">动态</span>
          </div>
        </div>

        <!-- 用户动态列表 -->
        <div class="posts">
          <h3 class="section-title">最新动态</h3>
          <div class="post-item" v-for="post in userPosts" :key="post.id">
            <div class="post-header">
              <img :src="userDetail.avatar" alt="avatar" class="post-avatar" />
              <div class="post-info">
                <span class="post-author">{{ userDetail.name }}</span>
                <span class="post-time">{{ post.time }}</span>
              </div>
            </div>
            <div class="post-content">
              <p class="post-text">{{ post.content }}</p>
              <div class="post-image">
                <img :src="post.image" alt="post" />
              </div>
            </div>
            <div class="post-actions">
              <span class="action">👍 {{ post.likes }}</span>
              <span class="action">💬 {{ post.comments }}</span>
              <span class="action">🔗</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 视频tab内容 -->
      <div v-else>
        <div class="video-list">
          <div class="video-card" v-for="(video, idx) in videoList" :key="idx">
            <div class="video-cover-wrap">
              <img :src="video.cover" class="video-cover" />
              <div class="video-duration">{{ video.duration }}</div>
            </div>
            <div class="video-title">{{ video.title }}</div>
            <div class="video-actions">
              <span class="video-like" :class="{ active: video.liked }" @click="toggleVideoLike(video)">
                {{ video.liked ? '❤️' : '👍' }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 详情页容器 */
.detail {
  /* 更改背景色为纯白色，增强整体一致性 */
  background: #fff;
  min-height: 100vh;
  padding-bottom: 80px;
  /* 添加字体族 */
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  /* 改用阴影替代边框，提升质感 */
  border-bottom: none;
  box-shadow: 0 1px 6px rgba(0,0,0,0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  margin-right: 12px;
  /* 增加返回按钮的可点击区域和交互反馈 */
  color: #333;
  transition: color 0.2s;
  height: 36px;
  width: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.back-btn:hover {
  background: #f5f5f5;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  /* 居中标题 */
  text-align: center;
  flex: 1;
  margin-right: 36px; /* 平衡返回按钮的宽度 */
}

/* 用户信息卡片 */
.user-card {
  background: #fff;
  /* 去除卡片边距和圆角，让卡片占满宽度 */
  margin: 0;
  border-radius: 0;
  padding: 20px;
  box-shadow: none;
  border-bottom: 1px solid #f0f0f0;
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.detail-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 16px;
  /* 更改边框颜色，使其更细腻 */
  border: 2px solid #1abc9c;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.user-level {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 操作按钮 */
.actions {
  display: flex;
  gap: 12px;
}

.follow-btn {
  flex: 1;
  background: #1abc9c;
  color: #fff;
  border: none;
  /* 增大圆角，符合截图风格 */
  border-radius: 24px;
  padding: 12px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}

.follow-btn.followed {
  background: #e0e0e0;
  color: #666;
}

.message-btn {
  background: #f0f0f0;
  color: #333;
  border: none;
  /* 增大圆角，符合截图风格 */
  border-radius: 24px;
  padding: 12px 16px;
  font-size: 16px;
  cursor: pointer;
}

/* tab切换栏样式 */
.detail-tabs {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 0;
}

.detail-tabs .tab {
  flex: 1;
  text-align: center;
  font-size: 16px;
  color: #888;
  padding: 14px 0 10px 0;
  cursor: pointer;
  font-weight: 500;
  /* 调整活动指示器样式 */
  border-bottom: 2px solid transparent;
  transition: color 0.2s, border-color 0.2s;
}

.detail-tabs .tab.active {
  color: #222;
  border-bottom: 2px solid #1abc9c;
  font-weight: 600;
  background: #fff;
}

/* 统计信息 */
.stats {
  display: flex;
  background: #fff;
  /* 改为贴边设计，去除卡片效果 */
  margin: 0;
  border-radius: 0;
  padding: 16px;
  box-shadow: none;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item {
  flex: 1;
  text-align: center;
  border-right: 1px solid #eee;
}

.stat-item:last-child {
  border-right: none;
}

.stat-number {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 动态列表 */
.posts {
  background: #fff;
  /* 改为贴边设计，去除卡片效果 */
  margin: 0;
  border-radius: 0;
  padding: 16px;
  box-shadow: none;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

.post-item {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
  margin-bottom: 16px;
}

.post-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.post-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
}

.post-info {
  flex: 1;
}

.post-author {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-content {
  margin-bottom: 12px;
}

.post-text {
  font-size: 15px;
  color: #333;
  line-height: 1.5;
  margin: 0 0 12px 0;
}

.post-image img {
  width: 100%;
  border-radius: 8px;
  object-fit: cover;
}

.post-actions {
  display: flex;
  gap: 16px;
}

.action {
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.tab-content {
  /* 改为白色背景 */
  background: #fff;
  min-height: 300px;
  padding-bottom: 20px;
}

/* 视频卡片列表样式 */
.video-list {
  display: flex;
  flex-wrap: wrap;
  gap: 14px 10px;
  padding: 18px 10px 0 10px;
}

.video-card {
  width: calc(50% - 5px);
  background: #fff;
  border-radius: 10px;
  /* 轻微阴影效果 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  margin-bottom: 2px;
  display: flex;
  flex-direction: column;
}

.video-cover-wrap {
  width: 100%;
  aspect-ratio: 1.5/1;
  background: #eee;
  overflow: hidden;
  position: relative;
}

.video-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.video-title {
  font-size: 15px;
  color: #222;
  font-weight: 500;
  margin: 8px 10px 0 10px;
  min-height: 36px;
  line-height: 1.2;
}

.video-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 10px 8px 0;
  font-size: 18px;
  color: #888;
}

.video-like {
  cursor: pointer;
}

.video-like.active {
  color: #ff5252;
}

/* 添加底部安全区域，防止内容被底部导航栏遮挡 */
.tab-content {
  padding-bottom: 60px;
}

/* 添加点赞按钮互动效果 */
.action:hover, .video-like:hover {
  color: #1abc9c;
}

/* 优化图片加载效果 */
img {
  transition: opacity 0.3s;
}

img.loading {
  opacity: 0.5;
}

.chat-btn {
  background: #fff;
  color: #1abc9c;
  border: 1px solid #1abc9c;
  border-radius: 50%;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8px;
  font-size: 22px;
  cursor: pointer;
  transition: all 0.3s;
}
.chat-btn:hover {
  background: #1abc9c;
  color: #fff;
}
</style>